<template>
  <div class="panoramic-container">
    <!-- 头部控制栏 -->
    <div class="camera-header">
      <div class="header-left">
        <el-icon class="camera-icon"><View /></el-icon>
        <span class="camera-title">全景视图</span>
      </div>
      
      <div class="header-controls">
        <button class="control-btn" @click="toggleFullscreen">
          <el-icon><FullScreen /></el-icon>
        </button>
        <button class="control-btn" @click="takeScreenshot">
          <el-icon><Camera /></el-icon>
        </button>
      </div>
    </div>
    
    <!-- 全景视频区域 -->
    <div class="panoramic-video" ref="videoContainer">
      <video 
        ref="videoElement"
        class="panoramic-feed"
        autoplay
        muted
        playsinline
        @mousedown="startDrag"
        @mousemove="onDrag"
        @mouseup="endDrag"
        @mouseleave="endDrag"
        @loadedmetadata="handleVideoLoaded"
        @error="handleVideoError"
      ></video>
      
      <!-- 连接状态指示器 -->
      <div v-if="!isConnected && !isConnecting" class="connection-status error">
        <el-icon><Warning /></el-icon>
        <span>全景视频流未连接</span>
      </div>
      
      <div v-if="isConnecting" class="connection-status connecting">
        <el-icon class="loading-icon"><Loading /></el-icon>
        <span>正在连接...</span>
      </div>
      
      <!-- 视频叠加信息 -->
      <div class="video-overlay" v-if="isConnected">
        <div class="video-info">
          <span class="resolution">{{ videoResolution }} • {{ videoFps }}FPS</span>
        </div>
        <div class="live-indicator">
          <span class="live-dot"></span>
          <span class="live-text">实时</span>
        </div>
      </div>
    </div>
    
    <!-- 控制面板区域 -->
    <div class="control-panel">
      <!-- PTZ控制区域 -->
      <div class="ptz-section">
        <!-- 上方向键 -->
        <button class="ptz-btn" @click="moveUp">
          <el-icon><ArrowUp /></el-icon>
        </button>
        
        <!-- 左右方向键 -->
        <div class="ptz-row">
          <button class="ptz-btn" @click="moveLeft">
            <el-icon><ArrowLeft /></el-icon>
          </button>
          <button class="ptz-btn active" @click="resetPosition">
            <el-icon><Aim /></el-icon>
          </button>
          <button class="ptz-btn" @click="moveRight">
            <el-icon><ArrowRight /></el-icon>
          </button>
        </div>
        
        <!-- 下方向键 -->
        <button class="ptz-btn" @click="moveDown">
          <el-icon><ArrowDown /></el-icon>
        </button>
      </div>
      
      <!-- 缩放控制 -->
      <div class="zoom-section">
        <button class="zoom-btn" @click="zoomOut">
          <el-icon><ZoomOut /></el-icon>
        </button>
        <button class="zoom-btn" @click="zoomIn">
          <el-icon><ZoomIn /></el-icon>
        </button>
      </div>
      
      <!-- 快捷视角调整按钮 -->
      <div class="view-shortcuts">
        <button 
          class="view-shortcut-btn" 
          :class="{ active: currentView === 'front' }"
          @click="setView('front')"
        >
          前视
        </button>
        <button 
          class="view-shortcut-btn" 
          :class="{ active: currentView === 'back' }"
          @click="setView('back')"
        >
          后视
        </button>
        <button 
          class="view-shortcut-btn" 
          :class="{ active: currentView === 'left' }"
          @click="setView('left')"
        >
          左侧
        </button>
        <button 
          class="view-shortcut-btn" 
          :class="{ active: currentView === 'right' }"
          @click="setView('right')"
        >
          右侧
        </button>
        <button 
          class="view-shortcut-btn" 
          :class="{ active: currentView === 'panoramic' }"
          @click="setView('panoramic')"
        >
          全景
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { 
  View, FullScreen, Camera, 
  ArrowUp, ArrowDown, ArrowLeft, ArrowRight, 
  Aim, ZoomIn, ZoomOut, Warning, Loading 
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { loadSceneConfig, getCameraConfig } from '@/utils/configLoader'

const videoContainer = ref(null)
const videoElement = ref(null)
const isConnected = ref(false)
const isConnecting = ref(false)
const videoResolution = ref('360°')
const videoFps = ref('30')

// 配置相关
const cameraConfig = ref(null)
const whepUrl = ref('')

// WebRTC 相关
const peerConnection = ref(null)

const dragState = reactive({
  isDragging: false,
  startX: 0,
  startY: 0,
  currentX: 0,
  currentY: 0
})

const cameraPosition = reactive({
  pan: 0,
  tilt: 0,
  zoom: 1
})

const currentView = ref('panoramic')

// 初始化配置
const initializeConfig = () => {
  try {
    // 配置已经在 main.js 中预加载，直接获取
    cameraConfig.value = getCameraConfig('panoramicCamera')
    
    if (cameraConfig.value?.whepUrl) {
      whepUrl.value = cameraConfig.value.whepUrl
      console.log('全景摄像头配置:', cameraConfig.value)
      return true
    } else {
      throw new Error('未找到全景摄像头配置')
    }
  } catch (error) {
    console.error('全景配置初始化失败:', error)
    ElMessage.error('全景摄像头配置加载失败')
    return false
  }
}

// WebRTC 连接函数
const connectWebRTC = async () => {
  if (isConnecting.value || isConnected.value) return
  
  if (!whepUrl.value) {
    ElMessage.error('全景摄像头配置未加载，无法连接')
    return
  }
  
  try {
    isConnecting.value = true
    console.log('开始连接全景 WebRTC 视频流...', whepUrl.value)
    
    // 创建 RTCPeerConnection
    peerConnection.value = new RTCPeerConnection({
      iceServers: [
        { urls: 'stun:stun.l.google.com:19302' },
        { urls: 'stun:stun1.l.google.com:19302' }
      ]
    })

    // 处理接收到的媒体流
    peerConnection.value.ontrack = (event) => {
      console.log('接收到全景媒体流')
      if (videoElement.value && event.streams[0]) {
        videoElement.value.srcObject = event.streams[0]
        isConnected.value = true
        isConnecting.value = false
        ElMessage.success('全景视频流连接成功')
      }
    }

    // 处理连接状态变化
    peerConnection.value.onconnectionstatechange = () => {
      const state = peerConnection.value?.connectionState
      console.log('全景视频连接状态:', state)
      
      if (state === 'connected') {
        isConnected.value = true
        isConnecting.value = false
      } else if (state === 'disconnected' || state === 'failed') {
        isConnected.value = false
        isConnecting.value = false
        ElMessage.error('全景视频流连接断开')
      }
    }

    // 处理 ICE 连接状态
    peerConnection.value.oniceconnectionstatechange = () => {
      const state = peerConnection.value?.iceConnectionState
      console.log('全景视频 ICE 连接状态:', state)
    }

    // 创建 offer
    const offer = await peerConnection.value.createOffer({
      offerToReceiveVideo: true,
      offerToReceiveAudio: true
    })
    
    await peerConnection.value.setLocalDescription(offer)

    // 发送 WHEP 请求
    const response = await fetch(whepUrl.value, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/sdp'
      },
      body: offer.sdp
    })

    if (!response.ok) {
      throw new Error(`全景视频 WHEP 请求失败: ${response.status} ${response.statusText}`)
    }

    const answerSdp = await response.text()
    
    // 设置远程描述
    await peerConnection.value.setRemoteDescription(new RTCSessionDescription({
      type: 'answer',
      sdp: answerSdp
    }))

    console.log('全景 WebRTC 连接建立成功')
    
  } catch (error) {
    console.error('全景 WebRTC 连接失败:', error)
    isConnecting.value = false
    isConnected.value = false
    ElMessage.error(`全景视频连接失败: ${error.message}`)
  }
}

// 断开 WebRTC 连接
const disconnectWebRTC = () => {
  if (peerConnection.value) {
    peerConnection.value.close()
    peerConnection.value = null
  }
  
  if (videoElement.value) {
    videoElement.value.srcObject = null
  }
  
  isConnected.value = false
  isConnecting.value = false
  console.log('全景 WebRTC 连接已断开')
}

// 重新连接
const reconnectWebRTC = async () => {
  disconnectWebRTC()
  await new Promise(resolve => setTimeout(resolve, 1000)) // 等待1秒
  await connectWebRTC()
}

const toggleFullscreen = () => {
  if (document.fullscreenElement) {
    document.exitFullscreen()
  } else {
    videoContainer.value?.requestFullscreen()
  }
}

const takeScreenshot = () => {
  if (!videoElement.value || !isConnected.value) {
    ElMessage.warning('请先连接全景视频流')
    return
  }
  
  try {
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')
    
    canvas.width = videoElement.value.videoWidth
    canvas.height = videoElement.value.videoHeight
    
    ctx.drawImage(videoElement.value, 0, 0)
    
    // 下载截图
    const link = document.createElement('a')
    link.download = `panoramic_screenshot_${new Date().getTime()}.png`
    link.href = canvas.toDataURL()
    link.click()
    
    ElMessage.success('全景截图已保存')
  } catch (error) {
    console.error('全景截图失败:', error)
    ElMessage.error('全景截图失败')
  }
}

const handleVideoLoaded = () => {
  console.log('全景视频加载完成')
  if (videoElement.value) {
    videoResolution.value = `${videoElement.value.videoWidth}x${videoElement.value.videoHeight}`
  }
}

const handleVideoError = (error) => {
  console.error('全景视频播放错误:', error)
  ElMessage.error('全景视频播放失败')
}

// 拖拽控制
const startDrag = (event) => {
  dragState.isDragging = true
  dragState.startX = event.clientX
  dragState.startY = event.clientY
}

const onDrag = (event) => {
  if (!dragState.isDragging) return
  
  const deltaX = event.clientX - dragState.startX
  const deltaY = event.clientY - dragState.startY
  
  cameraPosition.pan += deltaX * 0.5
  cameraPosition.tilt += deltaY * 0.5
  
  dragState.startX = event.clientX
  dragState.startY = event.clientY
  
  updateCameraView()
}

const endDrag = () => {
  dragState.isDragging = false
}

// PTZ控制
const moveUp = () => {
  cameraPosition.tilt -= 10
  updateCameraView()
}

const moveDown = () => {
  cameraPosition.tilt += 10
  updateCameraView()
}

const moveLeft = () => {
  cameraPosition.pan -= 10
  updateCameraView()
}

const moveRight = () => {
  cameraPosition.pan += 10
  updateCameraView()
}

const resetPosition = () => {
  cameraPosition.pan = 0
  cameraPosition.tilt = 0
  cameraPosition.zoom = 1
  updateCameraView()
}

const zoomIn = () => {
  cameraPosition.zoom = Math.min(cameraPosition.zoom + 0.1, 3)
  updateCameraView()
}

const zoomOut = () => {
  cameraPosition.zoom = Math.max(cameraPosition.zoom - 0.1, 0.5)
  updateCameraView()
}

const updateCameraView = () => {
  // 这里可以发送PTZ控制命令到后端
  console.log('更新摄像头视角:', cameraPosition)
}

// 快捷视角切换
const setView = (view) => {
  currentView.value = view
  
  switch (view) {
    case 'front':
      cameraPosition.pan = 0
      cameraPosition.tilt = 0
      break
    case 'back':
      cameraPosition.pan = 180
      cameraPosition.tilt = 0
      break
    case 'left':
      cameraPosition.pan = -90
      cameraPosition.tilt = 0
      break
    case 'right':
      cameraPosition.pan = 90
      cameraPosition.tilt = 0
      break
    case 'panoramic':
      cameraPosition.pan = 0
      cameraPosition.tilt = 0
      cameraPosition.zoom = 0.8
      break
  }
  
  updateCameraView()
  console.log(`切换到${view}视角`)
}

onMounted(async () => {
  const configLoaded = initializeConfig()
  if (configLoaded) {
    await connectWebRTC()
  }
})

onUnmounted(() => {
  disconnectWebRTC()
})

// 暴露方法供父组件调用
defineExpose({
  connectWebRTC,
  disconnectWebRTC,
  reconnectWebRTC,
  takeScreenshot,
  initializeConfig,
  cameraConfig
})
</script>

<style scoped>
.panoramic-container {
  background: rgba(10, 25, 47, 0.9);
  backdrop-filter: blur(8px);
  border: 1px solid var(--border-color);
  border-radius: 6px;
  box-shadow: 0px 4px 12px 0px rgba(0, 0, 0, 0.2);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.camera-header {
  background: var(--secondary-bg);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 8px;
  height: 28px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 4px;
}

.camera-icon {
  color: var(--primary-blue);
  font-size: 14px;
}

.camera-title {
  color: var(--text-primary);
  font-size: 13px;
  font-weight: 500;
  line-height: 1;
}

.header-controls {
  display: flex;
  align-items: center;
  gap: 4px;
}

.control-btn {
  background: none;
  border: none;
  color: var(--text-secondary);
  cursor: pointer;
  padding: 2px;
  border-radius: 4px;
  transition: color 0.3s ease;
  font-size: 12px;
}

.control-btn:hover {
  color: var(--primary-blue);
}

.panoramic-video {
  position: relative;
  width: 100%;
  background: #000000;
  overflow: hidden;
  cursor: grab;
  flex: 1.18; /* 按照1.18的比例分配空间 */
  min-height: 0; /* 确保flex能够正确收缩 */
}

.panoramic-video:active {
  cursor: grabbing;
}

.panoramic-feed {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
  user-select: none;
  background: #000;
}

.connection-status {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  z-index: 10;
}

.connection-status.error {
  background: rgba(239, 68, 68, 0.9);
  color: white;
}

.connection-status.connecting {
  background: rgba(59, 130, 246, 0.9);
  color: white;
}

.loading-icon {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.video-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.5);
  padding: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.video-info {
  display: flex;
  align-items: center;
}

.resolution {
  color: var(--text-secondary);
  font-size: 12px;
}

.live-indicator {
  display: flex;
  align-items: center;
  gap: 4px;
}

.live-dot {
  width: 8px;
  height: 8px;
  background: #EF4444;
  border-radius: 50%;
  animation: blink 1s infinite;
}

.live-text {
  color: var(--text-secondary);
  font-size: 12px;
}

.control-panel {
  background: var(--secondary-bg);
  padding: 6px 8px;
  display: flex;
  flex-direction: column;
  justify-content: space-between; /* 均匀分布，充分利用垂直空间 */
  gap: 4px;
  flex: 1; /* 按照1的比例分配空间 */
  width: 100%; /* 填满整个窗口宽度 */
  min-height: 0; /* 确保flex能够正确收缩 */
  overflow: hidden; /* 防止内容溢出 */
}

.ptz-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
  flex-shrink: 0; /* 不允许收缩 */
}

.ptz-row {
  display: flex;
  align-items: center;
  gap: 6px;
}

.ptz-btn {
  width: 32px;
  height: 32px;
  background: var(--accent-bg);
  border: none;
  border-radius: 5px;
  color: var(--text-secondary);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  font-size: 14px;
}

.ptz-btn:hover {
  background: var(--primary-bg);
  color: var(--primary-blue);
}

.ptz-btn.active {
  background: var(--primary-blue);
  color: var(--text-primary);
}

.zoom-section {
  display: flex;
  justify-content: center;
  gap: 8px;
  align-items: center;
  flex-shrink: 0; /* 不允许收缩 */
  margin: 2px 0;
}

.zoom-btn {
  width: 34px;
  height: 30px;
  background: var(--accent-bg);
  border: none;
  border-radius: 5px;
  color: var(--text-secondary);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  font-size: 13px;
}

.zoom-btn:hover {
  background: var(--primary-bg);
  color: var(--primary-blue);
}

.view-shortcuts {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 3px;
  width: 100%;
  flex-shrink: 0; /* 不允许收缩 */
}

.view-shortcut-btn {
  padding: 4px 2px;
  background: var(--accent-bg);
  border: none;
  border-radius: 4px;
  color: var(--text-secondary);
  font-size: 10px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  text-align: center;
  min-height: 26px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.view-shortcut-btn:hover {
  background: var(--primary-bg);
  color: var(--primary-blue);
}

.view-shortcut-btn.active {
  background: var(--primary-blue);
  color: var(--text-primary);
}

@keyframes blink {
  0%, 50% {
    opacity: 1;
  }
  51%, 100% {
    opacity: 0.3;
  }
}
</style>